import router from './router';
import { getCache } from '@/utils/session';
import getPageTitle from '@/utils/getPageTitle';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { message } from 'ant-design-vue';
import store from './store';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

// 不需要权限验证的路由
const whiteList = ['/login', '/404', '/403', '/500'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);
  
  const token = getCache('TOKEN');
  
  // 白名单路由直接通过
  if (whiteList.includes(to.path)) {
    next();
    NProgress.done();
    return;
  }
  
  // 没有token跳转登录
  if (!token) {
    next(`/login?redirect=${to.path}`);
    NProgress.done();
    return;
  }
  
  // 已有路由权限直接通过
  const hasRoutes = store.state.permission.routes && store.state.permission.routes.length > 0;
  if (hasRoutes) {
    next();
    NProgress.done();
    return;
  }
  
  // 获取用户信息和路由权限
  try {
    const userInfo = store.state.user.accountInfo;
    if (!userInfo) {
      throw new Error('No user info');
    }
    await store.dispatch('permission/getRoutes', userInfo.role || '');
    // hack: 确保路由已完全加载
    if (to.path === '/login') {
      next('/novel/list');
    } else {
      next({ ...to, replace: true });
    }
  } catch (error) {
    console.error('Error getting user routes:', error);
    message.error('获取用户信息失败，请重新登录');
    next('/login');
  }
  NProgress.done();
});

router.afterEach(() => {
  NProgress.done();
});
